//
//  ZMComposeViewController.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/31.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import SnapKit

class ZMComposeViewController: UIViewController ,UITextViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.orange
        
        setupNav()
        
        setupUI()
        
        
        // Do any additional setup after loading the view.
    }

    //保存从相册中选取的图片
    var images:[UIImage] = [UIImage]()
    
    
    //懒加载导航控制器titleView
    fileprivate lazy var titleLabel : UILabel = {
    
        let title = UILabel()
        title.numberOfLines = 0
        
        title.textAlignment = .center
        
        if let userName = ZMUserAccountViewModel.sharedViewModel.userAccountModel?.name {
            let text = "发微博\n" + userName
            
            //调整用户名文子显示的颜色
            let attrString : NSMutableAttributedString = NSMutableAttributedString(string: text)
            
            let nameRange = (text as NSString).range(of: userName)
            
            attrString.addAttributes([NSForegroundColorAttributeName:UIColor.orange,NSFontAttributeName:UIFont.systemFont(ofSize: 14)], range: nameRange)
            
            title.attributedText = attrString
            
            
        }
        title.sizeToFit()
        return title
    }()
    //懒加载发微博按钮
    fileprivate lazy var sendStatusButton: UIButton = {
    
        let sendbtn = UIButton()
        sendbtn.isEnabled = false
        sendbtn.setTitle("发送", for: UIControlState.normal)
        sendbtn.setTitleColor(UIColor.white, for: UIControlState.normal)
        sendbtn.setTitleColor(UIColor.gray, for: UIControlState.disabled)
       
        sendbtn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange").stretchableImage(withLeftCapWidth: 5, topCapHeight: 5), for: UIControlState.normal)
        sendbtn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white").stretchableImage(withLeftCapWidth: 5, topCapHeight: 5), for: UIControlState.disabled)
        sendbtn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted").stretchableImage(withLeftCapWidth: 5, topCapHeight: 5), for: UIControlState.highlighted)
        
        sendbtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        
        //设置按钮的大小
        sendbtn.size = CGSize(width: 45, height: 30)
        
        //发送按钮单击事件
        sendbtn.addTarget(self, action:  #selector(sendStatusBtnClick), for: UIControlEvents.touchUpInside)
        
        sendbtn.adjustsImageWhenHighlighted = false
      //  sendbtn.sizeToFit()
        return sendbtn
    }()
    //懒加载textview
    fileprivate lazy var statusTextView: ZMTextView = {
        
        let textview  =  ZMTextView()
        
        textview.delegate = self;
        
        
        //设置textview响应的键盘是否显示纠错视图
        textview.autocorrectionType = .no //不显示纠错视图
        
        return textview
    }()
    
    //懒加载picview
    fileprivate lazy var pictureView : ZMPictureView = ZMPictureView()
    
    
    
    //懒加载底部工具条
    fileprivate lazy var toolBar : ZMToolBar = ZMToolBar()
    
    
    //懒加载底部工具条
    fileprivate lazy var emotionKeyBoard: ZMEmotionKeyBoard = {
        let emotionview = ZMEmotionKeyBoard(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.width, height: 216)))
        
      //  emotionview.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.width, height: 216))
        
        
        return emotionview
    
    }()
    
    //MARK:- 发送按钮点击事件
    func sendStatusBtnClick(){
        
        //获取文本内容
        let text  = statusTextView.text!
        print(text)
        //获取富文本对应的字符串
//        var result = ""
//        statusTextView.attributedText.enumerateAttributes(in: NSMakeRange(0, statusTextView.attributedText.length), options: []) { (info:[String : Any], range, _) in
//            //判断富文本中是否有文本附件
//            if let attachment = info["NSAttachment"] as? ZMTextAttachment{
//                //有文本附件  表示是有表情的富文本
//                let chs = attachment.emotionModel?.chs
//                result += chs
//            }else{
//                //没有包含图片的文本附件,这时直接将富文本转变成普通的文本对象
//                let text = statusTextView.attributedText.attributedSubstring(from: range).string
//                result += text
//            }
//            
//        }
        
        let emotionText = statusTextView.emotionText
        
         
        
        
        
        
        
    }
    
    
    
    //MARK:- 初始化导航控制器
    func setupNav(){
        //添加取消按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancleBtnClick))
        //添加titleview
        navigationItem.titleView = titleLabel
        //添加发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendStatusButton)
        
    }
    //MARK:- 初始化UI
    func setupUI(){
        
        //监听键盘frame的变化
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(info:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //监听表情按钮点击发出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(clickEmotionButton(noti:)), name: NSNotification.Name(ClickEmoticonButtonNotificationName), object: nil)
        //监听表情键盘中删除按钮点击发送的通知
        NotificationCenter.default.addObserver(self, selector: #selector(clickDeleteEmotionButton(noti:)), name: NSNotification.Name(ClickDeleteEmoticonButtonNotificationName), object: nil)
        
        
        
        
       view.addSubview(statusTextView)
        //添加底部工具条
        view.addSubview(toolBar)
        statusTextView.addSubview(pictureView)
        
        //设置约束
        statusTextView.snp.makeConstraints { (make) in
           make.top.leading.trailing.equalTo(self.view)
           make.bottom.equalTo(toolBar.snp.top)
            
            
        }
        toolBar.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(50)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(statusTextView).offset(100)
            make.centerX.equalTo(statusTextView)
            make.width.equalTo(statusTextView).offset(-10)
            make.height.equalTo(statusTextView.snp.width)
            
            //make.leading.trailing.equalTo(statusTextView)

        }
        
        //设置toolBar按钮单击事件
        toolBar.toolBarButtonClickClosure = {[unowned self] (sender, btnType)in

            switch btnType {
            case .picture:
                //图片
                print("图片")
                //展示相册图片管理器
                self.pictureClick()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
               //判断 如果textview的响应键盘是系统键盘就修改成自定的表情键盘,如果是表情键盘,在点击表情按钮的时候要修改成系统的键盘
                if self.statusTextView.inputView == nil{
                    self.statusTextView.inputView = self.emotionKeyBoard
                }else{
                    self.statusTextView.inputView = nil
                }
                //修该textview的响应键盘的时候还要调用下面两个方法才能显示自定义的键盘
                self.statusTextView.becomeFirstResponder()
                UIView.animate(withDuration: 0.35, animations: { 
                    self.statusTextView.reloadInputViews()
                    
                })
                
                
            case .add:
                print("加好")
            }
        }
        //点击添加图片按钮执行的闭包回调
        pictureView.clickAddCellClosure = {
            self.pictureClick()
        }
        
        
    }
    
    //MARK:- 监听表情键盘,表情按钮发送的通知
   @objc private func clickEmotionButton(noti:Notification){
        //获取通知参数,从参数中获取需要显示的表情模型数据
        let emotionModel = noti.object as! ZMEmotionModel
       statusTextView.insertEmotion(emotionModel: emotionModel)
    
           
    
    }
    //MARK:- 监听表情键盘中删除按钮发送的通知
    @objc private func clickDeleteEmotionButton(noti:Notification){
     
        statusTextView.deleteBackward()
    }
    
    
    //MARK:-通知 监听键盘frame变化
    @objc private func keyBoardFrameChange(info: Notification){
        let userInfo = info.userInfo!
        //获取键盘的frame
        let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        //工具条更新约束
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        //动画执行约束
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK:- 导航控制器  取消   按钮点击事件
    func cancleBtnClick(){
        self.view.endEditing(true)
        //点击取消按键
        self.dismiss(animated: true) {
            
        }
    }
    
    
    func pictureClick(){
        //示例化相册图片浏览器
        let pictureVC = UIImagePickerController()
        //设置浏览器的图片数据源
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //设置来源类型,真机使用相机,模拟器使用相册
            pictureVC.sourceType = .camera
        }else{
            pictureVC.sourceType = .photoLibrary
        }
        //设置浏览器的代理对象
        pictureVC.delegate = self
        //显示图片浏览控制器
        self.present(pictureVC, animated: true) { 
            
        }
        
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    //MARK:- 在当前控制器删除的时候,将其从通知中心移除,防止内存泄露
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

//MARK:-textview代理监听方法
extension ZMComposeViewController{
    
    func textViewDidChange(_ textView: UITextView) {
        self.sendStatusButton.isEnabled = textView.hasText
    }
    //将要拖拽的时候接触当前textview的第一响应者
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.statusTextView.resignFirstResponder()
    }
    
}

//MARK:-相册浏览器的代理方法
extension ZMComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
       // print(info)
        
        let image: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        //将选择后的图片压缩
        let scaleImage = image.scaleImage(scaleWidth: 100)
        //将压缩后的图片保存在数组中
        self.images.append(scaleImage)
        
        pictureView.addImage(image: scaleImage)
        
        //选择图片完成,需要手动消除图片浏览器控制器
        picker.dismiss(animated: true) { 
            
        }
    }
    
}



